/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import dao.FamiliaDAO;
import dao.FamiliaMateriaPrimaDAO;
import dao.MateriaPrimaDAO;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import model.Familia;
import model.FamiliaMateriaPrima;
import model.MateriaPrima;
import sisgp.SisMsg;

/**
 *
 * @author Sandro
 */
public class frmManutencaoMateriaFamilia extends javax.swing.JFrame {

    /**
     * Creates new form frmManutencaoMateriaFamilia
     */
    public frmManutencaoMateriaFamilia() {
        initComponents();
        setLocationRelativeTo( null );
    }
    
    private List<FamiliaMateriaPrima> ListaMateriasFamilia;  
    private List<MateriaPrima> ListaCombo;
    public Familia familiaSelecionada;
    private int indiceTabela;
    private FamiliaMateriaPrima MatSelecionada;

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        btnAcao = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(1000, 705));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Código", "Descrição", "Status"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, true, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        if (jTable1.getColumnModel().getColumnCount() > 0) {
            jTable1.getColumnModel().getColumn(1).setResizable(false);
            jTable1.getColumnModel().getColumn(2).setResizable(false);
        }

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/rodape_sisgp.png"))); // NOI18N
        jLabel1.setAlignmentY(0.0F);

        btnAcao.setText("Inativar");
        btnAcao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAcaoActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Matéria Prima", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 14), new java.awt.Color(0, 153, 51))); // NOI18N

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/check.png"))); // NOI18N
        jButton1.setText("Adicionar Matéria Prima");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 324, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(72, 72, 72)
                .addComponent(jButton1)
                .addContainerGap(138, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(21, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(16, 16, 16))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 905, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(830, 830, 830)
                            .addComponent(btnAcao))))
                .addContainerGap(31, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnAcao)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        
        int indiceCombo = jComboBox1.getSelectedIndex();
        
        msg.Info(""+indiceCombo, "teste");
        
        
        if(jComboBox1.getSelectedIndex() == 0){
            
            msg.Erro("É necessário selecionar a Matéria Prima!", "Atenção");
            
        }
        else{
            
            int resposta = JOptionPane.showConfirmDialog(this, "Realmente deseja adicionar esta Matéria Prima à Família?");                
            if (resposta==JOptionPane.YES_OPTION){
                    
                FamiliaMateriaPrima fammatpri = new FamiliaMateriaPrima();
                MateriaPrima matpri = new MateriaPrima();
                
                
                
                msg.Info("Indice selecionado: "+(indiceCombo-1), "teste");
                
                matpri = ListaCombo.get(indiceCombo-1);
                
                msg.Info(""+matpri.getDescricao(), "teste");
                
                fammatpri.setFamilia(familiaSelecionada);
                fammatpri.setMateriaPrima(matpri);
                fammatpri.setStatus(1);
                
                famprimaDAO.inserir(fammatpri);
                
                msg.Info("Matéria Prima adicionada com sucesso!", "Atenção");
                
               carregaCombo();
               carregaGrid();

            }
            
        }
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        
        //familiaSelecionada = famDAO.findById(frmConsultaFamiliasProdutos.codselecionado);
        
        carregaCombo();
        carregaGrid();
        
    }//GEN-LAST:event_formWindowActivated

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        
        int linha = jTable1.getSelectedRow();
        
        if(linha < 0){
            
            btnAcao.setEnabled(false);
            
        }else{
            
            btnAcao.setEnabled(true);
            
            FamiliaMateriaPrima fmp = ListaMateriasFamilia.get(linha);
            
            if(fmp.getStatus() ==1){
                btnAcao.setText("Inativar");
            }
            else{
                btnAcao.setText("Ativar");
            }
            
            indiceTabela = linha;
            MatSelecionada = fmp;

        }
        
    }//GEN-LAST:event_jTable1MouseClicked

    private void btnAcaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAcaoActionPerformed
        
        FamiliaMateriaPrima fmp = MatSelecionada;
        
        if(MatSelecionada.getStatus() == 1){
            fmp.setStatus(2);
        }
        else{
            fmp.setStatus(1);
        }
        
        famprimaDAO.update(fmp);
        
        carregaCombo();
        carregaGrid();
        
        
    }//GEN-LAST:event_btnAcaoActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmManutencaoMateriaFamilia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmManutencaoMateriaFamilia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmManutencaoMateriaFamilia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmManutencaoMateriaFamilia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmManutencaoMateriaFamilia().setVisible(true);
            }
        });
    }
    
    public void carregaGrid(){
        
        DefaultTableModel dados = (DefaultTableModel) jTable1.getModel();
        dados.setNumRows(0);
        
        for(FamiliaMateriaPrima fmp : ListaMateriasFamilia){
            
            String status = "";
            
            if(fmp.getStatus() == 1){
                status = "Ativo";
            }
            else{
                status  = "Inativo";
            }
            
            dados.addRow(new String[] {
                ""+fmp.getMateriaPrima().getCodigo(),
                ""+fmp.getMateriaPrima().getDescricao(),
                ""+status
            });
            
        }
        
        
    }
    
    public void carregaCombo(){
        
        List<FamiliaMateriaPrima> listfamprima = famprimaDAO.findMatPrimadaFamilia(familiaSelecionada.getCodigo());
        
        ListaMateriasFamilia = listfamprima;
        
        List<MateriaPrima> listmatprima = matpriDAO.findAll();
        List<MateriaPrima> listaNova = new ArrayList<>();

        
        for(MateriaPrima mp : listmatprima){
            
            int existe = 0;
            
            for(FamiliaMateriaPrima fmp : listfamprima){

                if(mp.getCodigo() == fmp.getMateriaPrima().getCodigo()){
                    existe =1;
                }

            }
            
            if(existe ==0){
                listaNova.add(mp);
            }
            
        }
        
        ListaCombo = listaNova;
        
        DefaultComboBoxModel combo_materias = new DefaultComboBoxModel();
        
        combo_materias.addElement("Selecione...");
        
        for(MateriaPrima mat : listaNova){
            
            combo_materias.addElement(mat.getDescricao());
            
        }
        
        jComboBox1.setModel(combo_materias);
        jComboBox1.setSelectedIndex(0);
        
    }

    MateriaPrimaDAO matpriDAO = new MateriaPrimaDAO();
    
    FamiliaMateriaPrimaDAO famprimaDAO = new FamiliaMateriaPrimaDAO();
    
    FamiliaDAO famDAO = new FamiliaDAO();
    
    SisMsg msg = new SisMsg();
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAcao;
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
